/*
 * Copyright 2008 Federal Emergency Management Agency
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0 
 *    
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 *  
 */
package gov.fema.hazus.bdc.client.general.location;

import gov.fema.hazus.bdc.shared.entity.Location;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LocationTextBoxKeyListener implements LocationTextBoxKeyListenerInterface {

	private Location location;
	
	public LocationTextBoxKeyListener(Location location)
	{
		this.location = location;
	}
	
	public void onFocus(Widget arg0) {
		// do nothing
	}

	public void onLostFocus(Widget arg0) {

		TextBox textBox = (TextBox) arg0;
		String value = textBox.getText();
		String boxName = textBox.getName();
		
		GWT.log("text box name=" + boxName, null);
		
		Double doubleValue = 0.0;
		try {
			doubleValue = Double.parseDouble(value);
		} catch (NumberFormatException e) {
			// swallow, let the blur handler warn the user
			GWT.log("value("+value+") was not a double", null);
		}
		
		if( boxName.equals(Location.FIELD_LATITUDE) )
		{
			GWT.log( Location.FIELD_LATITUDE + ": " + value, null);
			location.setLatitude(doubleValue);
		} else if ( boxName.equals( Location.FIELD_LONGITUDE ) ) {
			GWT.log( Location.FIELD_LONGITUDE + ": " + value, null);
			location.setLongitude(doubleValue);
		} else if ( boxName.equals( Location.FIELD_CENSUSBLOCK ) ) {
			GWT.log( Location.FIELD_CENSUSBLOCK + ": " + value, null);
			location.setCensusBlock(value);			
		} else if ( boxName.equals( Location.FIELD_CENSUSGROUP ) ) {
			GWT.log( Location.FIELD_CENSUSGROUP + ": " + value, null);
			location.setCensusGroup(value);
		} else if ( boxName.equals( Location.FIELD_CENSUSTRACT ) ) {
			GWT.log( Location.FIELD_CENSUSTRACT + ": " + value, null);
			location.setCensusTract(value);
		} else if ( boxName.equals( Location.FIELD_COUNTYFIPS ) ) {
			GWT.log( Location.FIELD_COUNTYFIPS + ": " + value, null);
			location.setCountyFIPS(value);
		} else {
			// do nothing
		}	
		
	}

	public void updateGeoLocation(Location location) {
		this.location = location;
	}

}
